package com.senyint.sys.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import com.senyint.sys.utils.log.Log;

public class CookieUtils {

	/**
	 * 保存Cookie到客户端 登录时调用
	 * 
	 * @param username 用户名
	 * @param password 密码
	 * @param res
	 */
	public static void saveCookie4Login(String username, String password, HttpServletResponse res, long cookie_maxage, String cookie_domainname, String cookie_webkey) {
		// cookie的有效期
		long validTime = System.currentTimeMillis() + (cookie_maxage * 1000);
		// MD5加密用户详细信息
		String cookieValueWithMd5 = DigestUtils.md5Hex(new StringBuffer().append(username).append(":").append(password).append(":").append(validTime).append(":").append(cookie_webkey).toString());
		// 将要被保存的完整的Cookie值
		String cookieValue = new StringBuffer().append(username).append(":").append(validTime).append(":").append(cookieValueWithMd5).toString();
		// 再一次对Cookie的值进行BASE64编码
		String cookieValueBase64 = new String(Base64.encodeBase64(cookieValue.getBytes()));
		// 开始保存Cookie
		Cookie cookie = new Cookie(cookie_domainname, cookieValueBase64);
		// 存两年(这个值应该大于或等于validTime)
		cookie.setMaxAge(60 * 60 * 24 * 365 * 2);
		// cookie有效路径是网站根目录
		cookie.setPath("/");
		// 向客户端写入
		res.addCookie(cookie);
	}

	/**
	 * 用户注销时,清除Cookie,在需要时可随时调用
	 * 
	 * @param res
	 */

	public static void clearCookie4Login(HttpServletResponse res, String cookie_domainname) {
		Cookie cookie = new Cookie(cookie_domainname, null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		res.addCookie(cookie);
	}

	/**
	 * 获取cookie 的值
	 * @param cookies
	 * @param cookieName
	 * @return
	 */
	public static String getCookieValue(Cookie[] cookies, String cookieName) {
		String cookieValue = null;
		if (cookies != null && StringUtils.isNotEmpty(cookieName)) {
			for (Cookie cookie : cookies) {
				if (cookieName.equals(cookie.getName())) {
					cookieValue = cookie.getValue();
					break;
				}
			}
		} else {
			Log.INSTANCE.getLog().error("cookies or cookieName is null,cookies:{},cookieName:{}", cookies, cookieName);
		}
		return cookieValue;
	}

}
